package com.example.musicplayer.fragment;

import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.text.Html;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.Space;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.example.musicplayer.R;
import com.example.musicplayer.activity.LoginActivity;
import com.example.musicplayer.activity.MusicActivity;
import com.example.musicplayer.activity.PlayerActivity;
import com.example.musicplayer.activity.RegisterActivity;
import com.example.musicplayer.activity.SongSheetActivity;
import com.example.musicplayer.adapter.ClockActivity;
import com.example.musicplayer.adapter.FindRankAdapter;
import com.example.musicplayer.adapter.MainTabMyAdapter;
import com.example.musicplayer.adapter.MusicListAdapter;
import com.example.musicplayer.adapter.RecommendListAdapter;
import com.example.musicplayer.adapter.StopActicity;
import com.example.musicplayer.bean.Album;
import com.example.musicplayer.bean.Song;
import com.example.musicplayer.square.Square;
import com.youth.banner.Banner;
import com.youth.banner.adapter.BannerAdapter;
import com.youth.banner.adapter.BannerImageAdapter;
import com.youth.banner.holder.BannerImageHolder;
import com.youth.banner.listener.OnBannerListener;

import org.jetbrains.annotations.NotNull;


import java.io.IOException;
import java.io.InputStream;
import java.io.Serializable;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

import static android.content.ContentValues.TAG;

/**
 * A simple {@link Fragment} subclass.
 * Use the {@link MainTabFindFragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class MainTabFindFragment extends Fragment {

    // TODO: Rename parameter arguments, choose names that match
    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";

    // TODO: Rename and change types of parameters
    private String mParam1;
    private String mParam2;

    public MainTabFindFragment() {
        // Required empty public constructor
    }

    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     *
     * @param param1 Parameter 1.
     * @param param2 Parameter 2.
     * @return A new instance of fragment MainTabFindFragment.
     */
    // TODO: Rename and change types and number of parameters
    public static MainTabFindFragment newInstance(String param1, String param2) {
        MainTabFindFragment fragment = new MainTabFindFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }


    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment_main_tab_find, container, false);
    }

    //组件初始化
    List<Integer> bannerList;
    Banner banner_find_main;
    ListView lv_find_rank_hot;
    List<Song> rankListHot = new ArrayList<>();
    FindRankAdapter findrankadapter;
    RecommendListAdapter recommendListAdapter;
    ImageView text1;
    private TextView text;
    private ImageView iv_find_album;
    private ImageView iv_find_daily;
    private RecyclerView rv_fragment_find_recommend;

    private List<Album> albumList;
    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        text1 = (ImageView) getView().findViewById(R.id.iv_find_time);
        banner_find_main = getView().findViewById(R.id.banner_find_main);
        lv_find_rank_hot =(ListView)getView().findViewById(R.id.lv_find_rank_hot);
        iv_find_album= (ImageView) getView().findViewById(R.id.iv_find_album);
        iv_find_daily = (ImageView) getView().findViewById(R.id.iv_find_daily);
        iv_find_daily.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String url = getString(R.string.web_ip)+"/list/recommend/daily";
                OkHttpClient okHttpClient = new OkHttpClient();
                final Request request = new Request.Builder()
                        .url(url)
                        .get()
                        .build();
                Call call = okHttpClient.newCall(request);
                call.enqueue(new Callback() {
                    @Override
                    public void onFailure(@NotNull Call call, @NotNull IOException e) {

                    }

                    @Override
                    public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
                        String json = response.body().string();
                        System.out.println(json);
                        List<HashMap> list =JSON.parseArray(json, HashMap.class);
                        for(int i=0;i<list.size();i++){
                            Album album  = new Album();
                            album.setName(list.get(i).get("name").toString());
                            album.setNumber(Integer.parseInt(list.get(i).get("number").toString()));
                            String url = getString(R.string.web_ip)+"/songs/all/"+list.get(i).get("id");
                            OkHttpClient okHttpClient = new OkHttpClient();
                            final Request request = new Request.Builder()
                                    .url(url)
                                    .get()
                                    .build();
                            okHttpClient.newCall(request).enqueue(new Callback() {
                                @Override
                                public void onFailure(@NotNull Call call, @NotNull IOException e) {
                                    Log.d(TAG, "onFailure: 网络请求获取歌单全部歌曲失败");
                                }

                                @Override
                                public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
                                    Log.d(TAG, "onFailure: 网络请求获取歌单全部歌曲成功");
                                    String json = response.body().string();
                                    List<HashMap> list =JSON.parseArray(json, HashMap.class);
                                    List<Song> songList = new ArrayList<Song>();
                                    for(HashMap k:list){
                                        Song oneSong = new Song();
                                        oneSong.song = (String)k.get("song");
                                        oneSong.singer = (String)k.get("singer");
                                        oneSong.duration = (Integer) k.get("duration");
                                        oneSong.path = (String) k.get("path");
                                        oneSong.albumCoverPath = (String) k.get("album_cover_path");
                                        oneSong.id = (Integer) k.get("id");
                                        songList.add(oneSong);
                                    }
                                    album.setSongList(songList);
                                    if(album.getSongList().isEmpty()){
                                        album.setAlbumCover(getAlbumArt(0));
                                    }else{
                                        String url = getString(R.string.web_ip)+"/cover/"+album.getSongList().get(0).id;
                                        album.setAlbumCover(getImageFromNetByUrl(url));
                                    }
                                    Intent intent = new Intent(getContext(), MusicActivity.class);
                                    intent.putExtra("album",(Serializable)album);
                                    intent.putExtra("isWEBAlbum",true);
                                    getContext().startActivity(intent);


                                }
                            });
                        }
                    }
                });
            }
        });

        albumList = new ArrayList<>();
        //推荐rv设置
        rv_fragment_find_recommend = (RecyclerView) getView().findViewById(R.id.rv_fragment_find_recommend);
        LinearLayoutManager ms= new LinearLayoutManager(getContext());
        ms.setOrientation(LinearLayoutManager.HORIZONTAL);
        rv_fragment_find_recommend.setLayoutManager(ms);
        recommendListAdapter = new RecommendListAdapter(this,albumList);
        rv_fragment_find_recommend.setAdapter(recommendListAdapter);
        String url = getString(R.string.web_ip)+"/list/recommend";
        OkHttpClient okHttpClient = new OkHttpClient();
        final Request request = new Request.Builder()
                .url(url)
                .get()
                .build();
        Call call = okHttpClient.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(@NotNull Call call, @NotNull IOException e) {

            }

            @Override
            public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
                String json = response.body().string();
                System.out.println(json);
                List<HashMap> list =JSON.parseArray(json, HashMap.class);
                for(int i=0;i<list.size();i++){
                    Album album  = new Album();
                    album.setName(list.get(i).get("name").toString());
                    album.setNumber(Integer.parseInt(list.get(i).get("number").toString()));
                    String url = getString(R.string.web_ip)+"/songs/all/"+list.get(i).get("id");
                    OkHttpClient okHttpClient = new OkHttpClient();
                    final Request request = new Request.Builder()
                            .url(url)
                            .get()
                            .build();
                    okHttpClient.newCall(request).enqueue(new Callback() {
                        @Override
                        public void onFailure(@NotNull Call call, @NotNull IOException e) {
                            Log.d(TAG, "onFailure: 网络请求获取歌单全部歌曲失败");
                        }

                        @Override
                        public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
                            Log.d(TAG, "onFailure: 网络请求获取歌单全部歌曲成功");
                            String json = response.body().string();
                            List<HashMap> list =JSON.parseArray(json, HashMap.class);
                            List<Song> songList = new ArrayList<Song>();
                            for(HashMap k:list){
                                Song oneSong = new Song();
                                oneSong.song = (String)k.get("song");
                                oneSong.singer = (String)k.get("singer");
                                oneSong.duration = (Integer) k.get("duration");
                                oneSong.path = (String) k.get("path");
                                oneSong.albumCoverPath = (String) k.get("album_cover_path");
                                oneSong.id = (Integer) k.get("id");
                                songList.add(oneSong);
                            }
                            album.setSongList(songList);
                            if(album.getSongList().isEmpty()){
                                album.setAlbumCover(getAlbumArt(0));
                            }else{
                                String url = getString(R.string.web_ip)+"/cover/"+album.getSongList().get(0).id;
                                album.setAlbumCover(getImageFromNetByUrl(url));
                            }
                            albumList.add(album);
                            getActivity().runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    recommendListAdapter.notifyDataSetChanged();
                                }
                            });

                        }
                    });
                }
            }
        });






        findrankadapter = new FindRankAdapter(this,rankListHot);
        lv_find_rank_hot.setAdapter(findrankadapter);
        System.out.println(rankListHot);
        getRankList();
        lv_find_rank_hot.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Intent intent = new Intent(getActivity(), PlayerActivity.class);
                intent.putExtra("musicData",(Serializable)rankListHot);
                intent.putExtra("position",position);
                if(position>0){
                    intent.putExtra("isWEBAlbum",true);
                }
                startActivity(intent);
            }
        });
        iv_find_album.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(getContext(), SongSheetActivity.class);
                startActivity(intent);
            }
        });

        bannerList = new ArrayList();
        bannerList.add(R.drawable.banner1);
        bannerList.add(R.drawable.banner2);
        bannerList.add(R.drawable.banner3);
        bannerList.add(R.drawable.banner4);
        text1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(getContext(), Square.class);
//                Bundle bundle = this.getIntent().getExtras();
//                String manName = bundle.getString("username");
//                Bundle bund = new Bundle();
//                bund.putString("manname", manName);
                Bundle bund = new Bundle();
                bund.putString("manname", "用户1");
                bund.putString("manid", "00");
                intent.putExtras(bund);
                startActivity(intent);
            }
        });
        banner_find_main.setAdapter(new BannerImageAdapter(bannerList) {
            @Override
            public void onBindView(Object holder, Object data, int position, int size) {
                BannerImageHolder myHolder = (BannerImageHolder)holder;
                Integer myData = (Integer)data;
                myHolder.imageView.setImageResource(myData);
            }
        });
        banner_find_main.setOnBannerListener(new OnBannerListener() {
            @Override
            public void OnBannerClick(Object data, int position) {
                Toast.makeText(getContext(), "点击了" + (position + 1) + "张轮播图", Toast.LENGTH_SHORT).show();
            }


        });

    }

    private void getRankList(){
        String url = getString(R.string.web_ip)+"/songs/all/2";
        OkHttpClient okHttpClient = new OkHttpClient();
        final Request request = new Request.Builder()
                .url(url)
                .get()
                .build();
        okHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(@NotNull Call call, @NotNull IOException e) {
                Log.d(TAG, "onFailure: 网络请求获取hot排行榜歌单全部歌曲失败");
            }

            @Override
            public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
                Log.d(TAG, "onFailure: 网络请求获取hot排行榜歌单全部歌曲成功");
                String json = response.body().string();
                List<HashMap> list = JSON.parseArray(json, HashMap.class);
                List<Song> songList = new ArrayList<Song>();
                for(HashMap k:list){
                    Song oneSong = new Song();
                    oneSong.song = (String)k.get("song");
                    oneSong.singer = (String)k.get("singer");
                    oneSong.duration = (Integer) k.get("duration");
                    oneSong.path = (String) k.get("path");
                    oneSong.albumCoverPath = (String) k.get("album_cover_path");
                    oneSong.id = (Integer) k.get("id");
                    songList.add(oneSong);
                }
                rankListHot.clear();
                rankListHot.addAll(songList);
                getActivity().runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        findrankadapter.notifyDataSetChanged();
                    }
                });
            }
        });
    }
    private Bitmap getAlbumArt(long album_id) {
        String mUriAlbums = "content://media/external/audio/albums";
        String[] projection = new String[]{"album_art"};
        Cursor cur = getContext().getContentResolver().query(Uri.parse(mUriAlbums + "/" + Long.toString(album_id)), projection, null, null, null);
        String album_art = null;
        if (cur.getCount() > 0 && cur.getColumnCount() > 0) {
            cur.moveToNext();
            album_art = cur.getString(0);
        }
        cur.close();
        Bitmap bm = null;
        if (album_art != null) {
            bm = BitmapFactory.decodeFile(album_art);
        } else {
            bm = BitmapFactory.decodeResource(getResources(), R.drawable.musicpic);
        }
        return bm;
    }

    private  Bitmap getImageFromNetByUrl(final String src){
        try {
            Log.d("FileUtil", src);
            URL url = new URL(src);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setDoInput(true);
            connection.connect();
            InputStream input = connection.getInputStream();
            Bitmap myBitmap = BitmapFactory.decodeStream(input);
            connection.disconnect();
            return myBitmap;
        } catch (IOException e) {
            // Log exception
            return null;
        }

    }

}